$(document).ready(function() {
	TechniqueManager.init();
});
var listAllPost = [];
var currentPostPosition;
var TechniqueManager = {

	init : function() {
		var cb = function(resp) {
			// if ($.isEmptyObject(resp.session)) {
			// window.location = "/pages/login.jsp";
			// return;
			// } else {
			listAllPost = resp.listAllPost;
			TechniqueManager.loadListAllPost(listAllPost);
//			listAllPost.forEach(function(curPost) {
//				var ul = document.getElementById("list-post-ul");
//				var newLI = document.createElement("li");
//				ul.appendChild(newLI);
//				newLI.innerHTML = curPost.name;
//			});
			// dua ra first detail!
			currentPostPosition = 0;
			TechniqueManager.showDetailPost(currentPostPosition);
//			
//			// tao listener
			var listener = function(event) {
				var node = event.target;
				event.target.data = getNodeWithData(node);
				TechniqueManager.onClick(event);
			};
			$("#show-post-page").click(listener);
		}
		// }
		$.getJSON("getAllPost.action", null, cb);
	},
	loadListAllPost : function(listPost) {
		listPost.forEach(function(curPost, index){
			var ul = document.getElementById("list-news-ul");
			var newLI = document.createElement("li");
			ul.appendChild(newLI);
			newLI.innerHTML = curPost.name;
			newLI.setAttribute("data","to-detail");
			newLI.setAttribute("list_position", index);
		})
	},
	
	showDetailPost : function(currentPostPosition) {
		var curPost = listAllPost[currentPostPosition];
		
		var ten = document.getElementById("ten");
		var noi_dung = document.getElementById("noi_dung");
		ten.innerHTML = curPost.name;
		noi_dung.innerHTML = curPost.content;
		TechniqueManager.loadListComment();

	},
	createComment : function () {
		var commentObj = {};
		commentObj.name = $("#name").val();
		commentObj.email = $("#email").val();
		//commentObj.phone = $("#phone").val();
		commentObj.content = $("#content").val();
		commentObj.postId = listAllPost[currentPostPosition].id;
		var cb = function(resp){
			alert("them comment duoc oi!");
			
			
			var commentNode = $("#comment-li-templet").clone(true);
			setValue($(commentNode)[0], commentObj);
			$(commentNode).appendObj(commentObj);
			$("#list-comment-ul").append(commentNode);
		}
		$.getJSON("createNewComment.action",commentObj, cb);
	},
	loadListComment : function() {
		var curPostID = listAllPost[currentPostPosition].id;
		var cb = function(resp) {
			
			TechniqueManager.loadListAllComment(resp.listAllComment);
		}
		$.getJSON("listComment.action", {postId: curPostID}, cb);	
	},
	loadListAllComment : function(listComment ) {
		$("#list-comment-ul").html("");
		listComment.forEach(function(comment){
			var commentNode = $("#comment-li-templet").clone(true);
			commentNode.attr("id", "comment-"+comment.id);
			setValue($(commentNode)[0], comment);
			commentNode.removeClass("hidden");
	//		$(commentNode).appendObj(comment);
			$("#list-comment-ul").append(commentNode);
		})
	},
	onClick : function(event) {
		switch (event.target.data) {
		case "to-detail":
			var parentNode = getParentNode(event.target, "to-detail");
			currentPostPosition = parentNode.getAttribute("list_position");
			TechniqueManager.showDetailPost(currentPostPosition);
			break;
		case "add_comment":
			TechniqueManager.createComment();
			break;
		}
		
	},
}
function getNodeWithData(node) {
    if (node === null) {
        return;
    }

    if (node && node.attributes && node.attributes['data']) {
        return node.attributes['data'].value;
    }

    return this.getNodeWithData(node.parentNode);
}
function getValue (node, includeSkill) {
    var obj = {};

    if (includeSkill) {
        var skillObj = {};
        obj.listSkill = [];
    }

    function walk(node) {
        var child, next;
        switch (node.nodeType) {
            case 3: // Text node
                if (node.textContent.trim() && node.parentNode.getAttribute("name")) {
                    obj[node.parentNode.getAttribute("name")] = node.textContent.replace(/[\r\n]/g, "").replace(/\s+/g, " ").trim();
                }
                break;
            case 1: // Element node
            case 9: // Document node
                if (node.getAttribute("name")) {
                    if (node.getAttribute("select2")) {
                        obj[node.getAttribute("name")] = {id: $(node).select2('val'), text: $(node).select2('data') ? $(node).select2('data').text : ""};
                    }
                    else if (node.getAttribute("name") == "skillId" && includeSkill) {
                        skillObj.skillId = $(node).val();
                        skillObj.skillName = $(node).val();
                        if ($(getParentNode($(node)[0], "skill-item")).getObj())
                            skillObj.id = $(getParentNode($(node)[0], "skill-item")).getObj().id;
                        else skillObj.id = "";
                    } else if (node.nodeName === "INPUT" || node.nodeName === "TEXTAREA") {
                        if (node.getAttribute("name") == "birthday") {
                            obj[node.getAttribute("name")] = new Date($(node).datepicker('getDate')).toJSONLocal();
                        } else if (node.getAttribute("name") == "skillLevel" && includeSkill && skillObj.skillId) {
                            skillObj.skillLevel = node.value;
                            obj.listSkill.push(JSON.parse(JSON.stringify(skillObj)));
                        } else if (node.getAttribute("type") == "checkbox"){
                            obj[node.getAttribute("name")] = node.checked;
                        } else {
                            obj[node.getAttribute("name")] = node.value;
                        }
                    } else if (node.nodeName === "SELECT") {
                        obj[node.getAttribute("name")] = $(node).val();
                        break;
                    } else if (node.nodeName === "IMG") {
                        obj[node.getAttribute("name")] = node.src;
                        break;
                    }
                }
                child = node.firstChild;
                while (child) {
                    next = child.nextSibling;
                    walk(child);
                    child = next;
                }
                break;
        }
    }

    walk(node);
    return obj;
}
function setValue(node, obj) {
    function walk(node) {
        var child, next;
        switch (node.nodeType) {
            case 3: // Text node
                if (node.parentNode.getAttribute("name") && (obj[node.parentNode.getAttribute("name")]
                    && (obj[node.parentNode.getAttribute("name")]) != "" || obj[node.parentNode.getAttribute("name")] == 0)) {
                    node.textContent = obj[node.parentNode.getAttribute("name")];
                }
                break;
            case 1: // Element node
            case 9: // Document node
                if (node.getAttribute("name") && (obj[node.getAttribute("name")] &&
                    (obj[node.getAttribute("name")] != "") || obj[node.getAttribute("name")] == 0)) {
                    if (node.nodeName === "INPUT" || node.nodeName === "TEXTAREA") {
                        if (node.getAttribute("name") == "birthday") {
                            var date = new Date(obj[node.getAttribute("name")]);
                            $(node).datepicker('setDate', date);
                        } else
                            node.value = obj[node.getAttribute("name")];
                    } else if (node.nodeName === "SELECT") {
                        if (node.getAttribute("name") == "gender" || node.getAttribute("name") == "salaryOption") {

                            node.value = obj[node.getAttribute("name")];
                            if (node.getAttribute("name") == "salaryOption") {
                                $(node).trigger("change");
                            }
                        } else {
                            $(node).select2().select2("val", obj[node.getAttribute("name")]);
                        }
                        break;
                    } else if (node.nodeName === "IMG" && obj[node.getAttribute("name")] != "") {
                        node.src = obj[node.getAttribute("name")];
                        break;
                    } else if (!node.firstChild) {
                        node.textContent = obj[node.getAttribute("name")];
                    }
                }
                child = node.firstChild;
                while (child) {
                    next = child.nextSibling;
                    walk(child);
                    child = next;
                }
                break;
        }
    }

    walk(node);
    return obj;
}
function getParentNode(node, data) {
    if (node === null) {
        return;
    }
    if (node && node.attributes && node.attributes['data'] && node.attributes['data'].value == data) {
        return node;
    }
    return this.getParentNode(node.parentNode, data);
}
$.fn.appendObj = function (obj) {
    this[0].attributes["obj"] = obj;
};

$.fn.getObj = function (obj) {
    return this[0].attributes["obj"];
};